--
-- Author: yawei.zhu
-- Date: 2018-06-01 14:50:19
--
-- PvpChampionRender
--

local ClassRef = app.mvc.createRenderClass(...)

-- local arrWeek = {L("周一"), L("周二"), L("周三"), L("周四"), L("周五"), L("周六"), L("周日")}
local arrWeek = {L("champion_weekday1"), L("champion_weekday2"), L("champion_weekday3"), L("champion_weekday4"), L("champion_weekday5"), L("champion_weekday6"), L("champion_weekday7")}

--data =
function ClassRef.createWithData(data, node, index)
    local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.ChampionItemNode))
    if node == nil then
        ccui.Helper:doLayout(sprite)
    end
    sprite:init(data, index)
    return sprite
end
function ClassRef.create(node, index)
    return ClassRef.createWithData(nil, node, index)
end

--
function ClassRef:init(data, index)
    self.super.init(self, data)
    self:setContentSize(self._ui.Panel:getContentSize())

    self:setNodeEventEnabled(true)

    display.uiAddClick(self._ui.Panel, function(sender, eventType)
        executeFunc(self._onClick, self)
    end, true, 0.02)

    self._timeline = self:getTimeline()
    self._timeline:gotoFrameAndPause(0)
    -- self._timeline:play("search", true)

    self._characterNode = self._ui["Panel/Node_1"]

    self._imageBg = self._ui["Panel/Image"]
    self._choose = self._ui["Panel/choose"]
    self._firstTitle = self._ui["Panel/tlt"]
    self._secTitle = self._ui["Panel/text_mode"]
    self._weekDate = self._ui["Panel/date"]
    self._mask = self._ui["Panel/mask"]

    self._searchPanel = self._ui["Panel/Panel_search"]
    self._searchPanel:setTouchEnabled(false)
    -- self._searchBg = self._ui["Panel/Panel_search/bg"]
    -- self._searchAni = self._ui["Panel/Panel_search/mlg"]

    self._firstPanel = self._ui["Panel/Panel_first"]
    self._firstPanel:setTouchEnabled(false)
    self._firstDot = self._ui["Panel/Panel_first/dot"]
    self._firstDesc = self._ui["Panel/Panel_first/tlt"]
    self._firstName = self._ui["Panel/Panel_first/name"]

    self._signPanel = self._ui["Panel/Panel_sign"]
    self._signPanel:setTouchEnabled(false)
    self._signTime = self._ui["Panel/Panel_sign/time"]
    self._ui["Panel/Panel_sign/tlt"]:setString( L("Champion_match1") )

    self._startPanel = self._ui["Panel/Panel_start"]
    self._startPanel:setTouchEnabled(false)
    self._startTime = self._ui["Panel/Panel_start/time"]
    self._ui["Panel/Panel_start/tlt"]:setString( L("Champion_match2") )

    self._overPanel = self._ui["Panel/Panel_over"]
    self._overPanel:setTouchEnabled(false)
    self._overDesc = self._ui["Panel/Panel_over/tlt"]
    self._overDesc:setString( L("Champion_match3") )
    self._overDesc:getVirtualRenderer():setMaxLineWidth(170)


    self._teamFlag = self._ui["Panel/icon"]
    -- self:refresh()
end

function ClassRef:onExit()
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
end

function ClassRef:_tick(dt)

    -- 计算倒计时
    local remainedTime = 1
    if self._startPanel:isVisible() then
        remainedTime = self:setRegisterCountDown()
    elseif self._signPanel:isVisible() then
        remainedTime = self:setPrepareCountDown()
    end

    -- 倒计时结束，刷新页面
    if remainedTime <= 0 then
        self:refresh()
    end
end

-- 为了保持mvc结构，在refresh之前，先把throneGame存储起来
function ClassRef:setThroneGame(throneGame)
    self._throneGame = throneGame
end

function ClassRef:refresh()
    if not self._data then return end
    -- 移除定时器
    if self._cronsIdx then
        scheduler.cancelCron(self._cronsIdx)
        self._cronsIdx = nil
    end
    --clear
    self:clearItem()
    -- 标题显示
    self._firstTitle:setString("")
    self._secTitle:setString("")
    self._weekDate:setString(arrWeek[self._data.day])
    local throneConfig = GD:queryThroneByDay(self._data.day)
    if throneConfig then
        self._firstTitle:setString( L(throneConfig.name) )
        self._secTitle:setString( L(throneConfig.des) )
        self._imageBg:loadTexture( Res.ThroneBgPath .. throneConfig.picture .. ".png")
    end
    -- 获取当前周几
    local day = app:getWeekDay()

    -- 判断是否为比赛日
    if self._data.day < day then
        self:showFirstPanel()
    elseif self._data.day > day then
        self:showFirstPanel()
        self._weekDate:setOpacity(255 * 0.5)
        self._mask:setVisible(true)
    else 
        self._choose:setVisible(true) -- 当天选中框

        -- 已决出冠军 TOOD 直接根据throneGame里的isClosed来判断
        -- if app:sendMsg("PvpModel", "getChampionTeam") then
        --     self:showFirstPanel()
        --     return
        -- end

        -- 先判断时间点
        self.status = self._throneGame:checkChampionStatus()

        if self.status == Enums.ChampionStatus.NOT_OPEN then
            self._overPanel:setVisible(true)
            self._overDesc:setString( L("Champion_match4") )
        elseif self.status == Enums.ChampionStatus.BATTLE then
            self._overPanel:setVisible(true)
            self._overDesc:setString( L("Champion_match5") )
        elseif self.status == Enums.ChampionStatus.CLOSE then
            --赛事已结束
            self:showFirstPanel() 
        elseif self.status == Enums.ChampionStatus.REGISTER then
            self._startPanel:setVisible(true)
            self:setRegisterCountDown()
            if not self._throneGame:getRegister() then -- 未报名
                self._timeline:play("breath", true)
            else
                if self._throneGame:getMemCount() >= 3 then -- 队伍已满
                    self._teamFlag:setVisible(true)
                    if not self._playTeam then
                        self._playTeam = true
                        self._timeline:play("team", false)
                    else
                        self._timeline:gotoFrameAndPause(360)
                    end
                else -- 队伍未满
                    self._searchPanel:setVisible(true)
                    self._timeline:play("search", true)
                end
            end

        elseif self.status == Enums.ChampionStatus.PREPARE or self.status == Enums.ChampionStatus.ENTER then
            self._signPanel:setVisible(true)
            self:setPrepareCountDown()
        end

        -- 添加定时器
        self._cronsIdx = scheduler.newCron(handler(self, self._tick), 1, true)
    end

end

function ClassRef:setRegisterCountDown()
    local throneGame = self._throneGame
    local serverTime = app.session:getServerTime() or os.time()
    local remainedTime = throneGame.regCloseTime - serverTime
    if remainedTime < 0 then remainedTime = 0 end

    local hour = math.floor(remainedTime / 3600)
    local min = math.floor((remainedTime - hour * 3600) / 60)
    local sec = math.floor(remainedTime % 60)
    self._startTime:setString(string.format( L("Champion_match6"), hour, min, sec))

    return remainedTime
end

function ClassRef:setPrepareCountDown()
    local throneGame = self._throneGame
    local serverTime = app.session:getServerTime() or os.time()
    local remainedTime = throneGame.battleStartTime - serverTime
    if remainedTime < 0 then remainedTime = 0 end

    local hour = math.floor(remainedTime / 3600)
    local min = math.floor((remainedTime - hour * 3600) / 60)
    local sec = math.floor(remainedTime % 60)
    self._signTime:setString(string.format( L("Champion_match7"), hour, min, sec))

    return remainedTime
end


-- local PlayerAnimations = {"mapidle","mapwalk","style1","mapmove","angry","celebrate","confusion","happy","seriously"} -- 动画名称

function ClassRef:showFirstPanel()
    -- 判断是否有无卫冕冠军
    local baseInfo = self._data.baseInfo
    -- dump(self._data.baseInfo)
    if not baseInfo then return end

    self._firstPanel:setVisible(true)
    self._firstDesc:setString(L("champion_notice7"))
    self._firstName:setString( baseInfo.name )

    if self.isLoading then return end
    self.isLoading = true
    -- 显示人物，此处人物资源用异步加载
    baseInfo.inBattle = false
    baseInfo.mountID = 0
    
    local AvatarFactory = app:getClass("AvatarFactory")
    AvatarFactory.preloadHero(baseInfo, function()
        if tolua.isnull(self) then return end
        self.isLoading = false
        local character = AvatarFactory.createHero(baseInfo)
        self._characterNode:removeAllChildren()
        self._characterNode:addChild(character)
        character:playAni({name = "mapidle"})
        character:setScale(0.8)
    end)
end

function ClassRef:clearItem()
    self._timeline:gotoFrameAndPause(0)

    self._choose:setVisible(false)
    self._mask:setVisible(false)
    self._weekDate:setOpacity(255)

    self._searchPanel:setVisible(false)
    self._firstPanel:setVisible(false)
    self._signPanel:setVisible(false)
    self._startPanel:setVisible(false)
    self._overPanel:setVisible(false)
    
    self._teamFlag:setVisible(false)
    -- self._throneGame = nil
end

function ClassRef:getStatus()
    return self.status
end

function ClassRef:onBtnClick(cb)
    self._onClick = cb
end

function ClassRef:onOperate(cb)
    self._onOperate = cb
end

return ClassRef
